#!/bin/bash
# 日志智能监控系统

LOG_PATH="/var/log/a.log"         # 日志绝对路径
ALERT_THRESHOLD=5                 # 每分钟错误阈值
SLACK_WEBHOOK="https://hooks.slack.com/services/XXX"  # 报警渠道

# 异常检测核心逻辑
tail -F ${LOG_PATH} | while read line
do
  # 错误计数
  if [[ "$line" =~ "ERROR" ]]; then
    ((error_count++))
    echo "$(date '+%F %T') - 检测到错误: ${line:0:120}..." >> /var/log/monitor.log
  fi

  # 每分钟重置计数器
  if [[ "$(date +%S)" == "00" ]]; then
    if [[ $error_count -ge $ALERT_THRESHOLD ]]; then
      curl -X POST -H 'Content-type: application/json' \
        --data "{\"text\":\"🚨 日志告警：过去1分钟检测到 ${error_count} 个错误！\"}" \
        ${SLACK_WEBHOOK}
    fi
    error_count=0
  fi
done